package daoutil

import (
	"fmt"
	"reflect"
)

type SetNoResult struct {
	Id int
	No int
}

//SetNo: list is []struct. Set id to no in list,no start at 1
func SetNo(list interface{}, id, no int, idField string) []SetNoResult {
	if idField == "" {
		idField = "Id"
	}
	listV := reflect.ValueOf(list)
	l := listV.Len()
	if no > l {
		no = l
	}
	if no < 1 {
		no = 1
	}
	oldIndex := -1
	for i := 0; i < l; i++ {
		if id == listV.Index(i).FieldByName(idField).Interface() {
			oldIndex = i
			break
		}
	}
	if oldIndex == -1 || oldIndex+1 == no {
		return nil
	}
	steps := (oldIndex + 1) - no
	forward := true
	if steps < 0 {
		forward = false
		steps = -steps
	}
	steps++
	r := make([]SetNoResult, steps)
	r[0] = SetNoResult{Id: id, No: no}
	for i := 1; i < steps; i++ {
		r[i] = SetNoResult{}
		if forward {
			r[i].No = oldIndex - i + 2
			r[i].Id = int(listV.Index(oldIndex - i).FieldByName(idField).Int())
		} else {
			r[i].No = oldIndex + i
			r[i].Id = int(listV.Index(oldIndex + i).FieldByName(idField).Int())
		}
	}
	return r
}

func SetNoSqls(list interface{}, id, no int, idField, noField, table string) []string {
	rs := SetNo(list, id, no, idField)
	tmp := "update `" + table + "` set `" + noField + "`=%d where `" + idField + "`=%d"
	r := make([]string, len(rs))
	for i, v := range rs {
		r[i] = fmt.Sprintf(tmp, v.Id, v.No)
	}
	return r
}
